package com.hefan.user.task;

import com.hefan.schedule.model.ScheduleExecuteRecord;
import com.hefan.schedule.model.ScheduleServer;
import com.hefan.schedule.service.IScheduleExecuteRecordService;
import com.hefan.schedule.service.IScheduleTaskDeal;
import com.hefan.user.itf.WebUserWatchDayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by wangchao on 2016/12/28.
 * 用户观看时长定时任务
 */

@Service("userWatchTimeTask")
public class UserWatchTimeTask implements IScheduleTaskDeal {

  private static Logger logger = LoggerFactory.getLogger(UserWatchTimeTask.class);

  @Resource
  private IScheduleExecuteRecordService scheduleExecuteRecordService;
  @Resource
  private WebUserWatchDayService webUserWatchDayService;

  /**
   * 用户时长定时任务 0 5 0 * * ?
   *
   * @param scheduleServer
   * @author wangchao
   * @version 1.0.0
   * @since 2016/10/31 下午12:25:16
   */

  @Override
  public boolean execute(ScheduleServer scheduleServer) {
    ScheduleExecuteRecord scheduleExecuteRecord = new ScheduleExecuteRecord();
    scheduleExecuteRecord.setExecuteTime(new Date());
    long startTime = System.currentTimeMillis();
    boolean rst = true;
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH, -1);
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    String time = dateFormat.format(cal.getTime());
    int successCount = 0;
    int failCount = 0;
    try {
      List<Map<String, Object>> list = webUserWatchDayService.getWatchTimeByDay(time);
      if (!CollectionUtils.isEmpty(list)) {
        for (Map<String, Object> map : list)
          if (map.get("userId") != null && map.get("totalTime") != null) {
            try {
              //更新用户时长
              String userId = String.valueOf(map.get("userId"));
              long watchTime = Long.parseLong(String.valueOf(map.get("totalTime")));
              webUserWatchDayService.updateUserWatchTime(userId, watchTime, time);
              successCount++;

            } catch (Exception e) {
              failCount++;
              logger.error("统计用户{}时长{}异常", map.get("userId"), map.get("totalTime"), e);
            }
          }
      }
    } catch (Exception e) {
      logger.error("统计用户时长异常", e);
      rst = false;
    }
    long endTime = System.currentTimeMillis();
    scheduleExecuteRecord.setConsumingTime((endTime - startTime));
    scheduleExecuteRecord.setNextExecuteTime(scheduleServer.getNextRunStartTime());
    scheduleExecuteRecord.setTaskType(scheduleServer.getBaseTaskType());
    scheduleExecuteRecord.setStatus(rst ? (short) 1 : (short) 2);
    scheduleExecuteRecord.setExecuteResult(String.format("用户观看时长定时任务，成功处理%s条，处理失败%s条", successCount, failCount));
    scheduleExecuteRecord.setHostName(scheduleServer.getHostName());
    scheduleExecuteRecord.setIp(scheduleServer.getIp());
    scheduleExecuteRecordService.addScheduleExecuteRecord(scheduleExecuteRecord);
    return true;
  }
}

